package com.instagram.instadownloader.fragment;

import java.io.File;
import java.util.Date;

import org.apache.commons.io.FilenameUtils;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.instagram.instadownloader.BaseInstaDownloaderActivity;
import com.instagram.instadownloader.MainActivity;
import com.vine.vinedownloader.R;
import com.instagram.instadownloader.bookmark.BookmarkObject;
import com.instagram.instadownloader.bookmark.BookmarksManager;
import com.instagram.instadownloader.fetcher.FetcherData;
import com.instagram.instadownloader.fetcher.InstaVideoFetcher.OnFetcherListener;
import com.instagram.instadownloader.fetcher.VineVideoFetcher;
import com.instagram.instadownloader.fragment.base.InstagramFragment;
import com.instagram.instadownloader.history.HistoryManager;
import com.instagram.instadownloader.utils.ClipboardUtil;
import com.instagram.instadownloader.utils.DialogUtil;
import com.instagram.instadownloader.utils.DialogUtil.OnDialogListener;
import com.instagram.instadownloader.utils.DialogUtility;
import com.instagram.instadownloader.utils.IDefines;
import com.instagram.instadownloader.utils.InstaFileManager;
import com.instagram.instadownloader.utils.Launcher;
import com.instagram.instadownloader.utils.SdcardUtils;
import com.instagram.instadownloader.utils.SharedPrefs;
import com.instagram.instadownloader.utils.TextUtil;
import com.instagram.instadownloader.utils.UniversalImageLoader;
import com.instagram.instadownloader.utils.download.DownloadTask.OnDownloadListener;
import com.instagram.instadownloader.utils.download.HandlerDownload;

/**
 * The Class DownloadFragment.
 * 
 * @author HuanND
 */
public class DownloadFragment extends InstagramFragment implements OnClickListener {

    /** The m image fetcher. */
    private ImageView mImageFetcher;

    /** The m image video fetcher. */
    private ImageView mImageVideoFetcher;

    /** The m text view status. */
    private TextView mTextViewStatus;

    /** The m button repost. */
    private Button mButtonRepost;
    
    /** The m button share. */
    private ImageButton mButtonShare;

    /** The m edt url. */
    private AutoCompleteTextView mEdtUrl;

    /** The m layout download. */
    private View mLayoutDownload;
    /** The m progress dialog. */
    private ProgressDialog mProgressDialog;

    /** The m current fetcher data. */
    private FetcherData mCurrentFetcherData;

    private View layoutVideoPart, layoutImagePart;

    private String currentUrl = "";

    /*
     * (non-Javadoc)
     * 
     * @see com.instagram.instadownloader.fragment.base.BaseFragment#onCreateContentView
     * (android.view.LayoutInflater, android.view.ViewGroup)
     */
    @Override
    protected View onCreateContentView(LayoutInflater inflater, ViewGroup container) {
        View v = inflater.inflate(R.layout.fragment_download_tab, container, false);
        mTextViewStatus = (TextView) v.findViewById(R.id.tvStatus);
        mEdtUrl = (AutoCompleteTextView) v.findViewById(R.id.etURL);
        mImageFetcher = (ImageView) v.findViewById(R.id.imageViewImagePost);
        mImageVideoFetcher = (ImageView) v.findViewById(R.id.imageViewVideoPost);
        mLayoutDownload = v.findViewById(R.id.layoutDownload);
        mButtonRepost = (Button) v.findViewById(R.id.btnRepost);
        mButtonShare = (ImageButton) v.findViewById(R.id.btnShare);
        mProgressDialog = new ProgressDialog(getActivity());

        layoutVideoPart = v.findViewById(R.id.layoutVideoPart);
        layoutImagePart = v.findViewById(R.id.layoutImagePart);
        mProgressDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        showOrHideLayout(false);
        initParams(v);
        initListener(v);

        // getInstaActivity().getInstaDownloadManager().setOnProcessDownloadingListener(this);
        return v;
    }

    private enum UrlType {
        IMAGE, VIDEO, IMG_VDO, ERROR
    }

    /**
     * control show/hidden image/video preview box.
     * 
     * @param pType
     */
    private void handlerCheckUrl(UrlType pType) {
        RelativeLayout.LayoutParams param =
                new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT);
        switch (pType) {

            case IMAGE:
                layoutVideoPart.setVisibility(View.GONE);

                param.addRule(RelativeLayout.CENTER_HORIZONTAL);
                layoutImagePart.setLayoutParams(param);
                break;
            case VIDEO:
                layoutImagePart.setVisibility(View.GONE);
                param.addRule(RelativeLayout.CENTER_HORIZONTAL);
                layoutVideoPart.setLayoutParams(param);
                break;
            case IMG_VDO:
                if (layoutVideoPart.getVisibility() == View.GONE
                        || layoutVideoPart.getVisibility() == View.INVISIBLE) {
                    layoutVideoPart.setVisibility(View.VISIBLE);
                }
                param.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
                param.addRule(RelativeLayout.LEFT_OF, R.id.button1);
                layoutImagePart.setLayoutParams(param);

                RelativeLayout.LayoutParams param2 =
                        new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
                                RelativeLayout.LayoutParams.WRAP_CONTENT);
                param2.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                param2.addRule(RelativeLayout.RIGHT_OF, R.id.button1);
                layoutVideoPart.setLayoutParams(param2);
                break;
            case ERROR:
                layoutImagePart.setVisibility(View.GONE);
                layoutVideoPart.setVisibility(View.GONE);
                break;
        }
    }

    /**
     * Inits the params.
     * 
     * @param v the v
     */
    private void initParams(View v) {
        v.findViewById(R.id.rlImageView1).getLayoutParams().width = MainActivity.SCREEN_WIDTH / 3;
        v.findViewById(R.id.rlImageView1).getLayoutParams().height = (int) (MainActivity.SCREEN_WIDTH / 2.5);
        v.findViewById(R.id.rlImageView2).getLayoutParams().width = MainActivity.SCREEN_WIDTH / 3;
        v.findViewById(R.id.rlImageView2).getLayoutParams().height = (int) (MainActivity.SCREEN_WIDTH / 2.5);
    }

    /**
     * Inits the listener.
     * 
     * @param v the v
     */
    private void initListener(View v) {
        mImageFetcher.setOnClickListener(this);
        mImageVideoFetcher.setOnClickListener(this);
        mButtonRepost.setOnClickListener(this);
        mButtonShare.setOnClickListener(this);

        v.findViewById(R.id.btnDownload).setOnClickListener(this);
        v.findViewById(R.id.btnPasteURL).setOnClickListener(this);
        v.findViewById(R.id.btnImage).setOnClickListener(this);
        v.findViewById(R.id.btnVideo).setOnClickListener(this);
    }

    /**
     * Show or hide layout.
     * 
     * @param isShow the is show
     */
    public void showOrHideLayout(boolean isShow) {
        if (isShow) {
            mLayoutDownload.setVisibility(View.VISIBLE);
            mButtonRepost.setVisibility(View.VISIBLE);
            mButtonShare.setVisibility(View.VISIBLE);
        } else {
            mLayoutDownload.setVisibility(View.GONE);
            mButtonRepost.setVisibility(View.GONE);
            mButtonShare.setVisibility(View.GONE);
        }
    }

    /**
     * Start fetching url.
     * 
     * @param string the string
     */
    public void startFetchingUrl(final String string) {
//        InstaVideoFetcher localInstaVideoFetcher = new InstaVideoFetcher();
    	VineVideoFetcher localInstaVideoFetcher = new VineVideoFetcher();
        String uRLTobeFetched = localInstaVideoFetcher.validate(string);
        if (!"".equals(uRLTobeFetched)) {
            showDialog("fetching url...");
            localInstaVideoFetcher.fetch(uRLTobeFetched, new OnFetcherListener() {

                @Override
                public void onFetcherFail(String message) {
                    mCurrentFetcherData = null;
                    dismissDialog();
                }

                @Override
                public void onFetcherComplete(FetcherData data) {
                	mTextViewStatus.setText("Instagram video and image available");
                    dismissDialog();
                    SharedPrefs.getInstance().setBookmarkUrlPath(string);
                    showOrHideLayout(true);
                    mCurrentFetcherData = data;
                    View[] vg = {mImageFetcher, mImageVideoFetcher};
                    UniversalImageLoader.getInstance().loadImageView(vg, data.getImageUrl(),
                            MainActivity.SCREEN_WIDTH / 3, 0);
                    BookmarksManager.getInstance().updateImageUrl(currentUrl, data.getImageUrl());
                    if (mCurrentFetcherData.getVideoUrl() == null || mCurrentFetcherData.videoUrl.isEmpty()) {
                        handlerCheckUrl(UrlType.IMAGE);
                    } else {
                        handlerCheckUrl(UrlType.IMG_VDO);
                    }
                }
            });
            return;
        } else {
            mTextViewStatus.setText("Invalid Url");
            showOrHideLayout(false);
        }
    }

    /**
     * On paste copied link.
     */
    private void onPasteCopiedLink() {
        hideKeyBoard(mEdtUrl);
        // try {
        // FragmentActivity localFragmentActivity = getActivity();
        // getActivity();
        // ClipboardManager localClipboardManager = (ClipboardManager)
        // localFragmentActivity
        // .getSystemService("clipboard");
        // if (localClipboardManager.getText().equals("")) {
        // this.mEdtUrl.setText("http://instagram.com/p/");
        // saveUrlShare("http://instagram.com/p/");
        // return;
        // }
        // this.mEdtUrl.setText(localClipboardManager.getText());
        // saveUrlShare(localClipboardManager.getText().toString());
        // startFetchingUrl(mEdtUrl.getText().toString());
        // return;
        // } catch (Exception localException) {
        // this.mEdtUrl.setText("http://instagram.com/p/");
        // saveUrlShare("http://instagram.com/p/");
        // }
        String textInClipboard = ClipboardUtil.getText(getActivity());
        if (textInClipboard == null || textInClipboard.equals("")) {
            this.mEdtUrl.setText("http://instagram.com/p/");
            saveUrlShare("http://instagram.com/p/");
            return;
        }
        this.mEdtUrl.setText(textInClipboard);
        saveUrlShare(textInClipboard);
        startFetchingUrl(mEdtUrl.getText().toString());
        currentUrl = mEdtUrl.getText().toString();
        BookmarksManager.getInstance().addBookmark(new BookmarkObject(mEdtUrl.getText().toString(), ""));
    }

    private void saveUrlShare(String url) {
        ((BaseInstaDownloaderActivity) getActivity()).setShareInstaUrl(url);
    }

    /**
     * Hide key board.
     * 
     * @param paramView the param view
     */
    protected void hideKeyBoard(View paramView) {
        try {
            ((InputMethodManager) getActivity().getSystemService("input_method")).hideSoftInputFromWindow(
                    paramView.getWindowToken(), 0);
            return;
        } catch (Exception localException) {
            Log.e("InstaDownloadFragment", localException.toString());
        }
    }

    /**
     * Show dialog.
     * 
     * @param message the message
     */
    public void showDialog(String message) {
        if (!mProgressDialog.isShowing()) {
            mProgressDialog.setMessage(message);
            mProgressDialog.show();
        }
    }

    /**
     * Dismiss dialog.
     */
    public void dismissDialog() {
        if (mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }

    /**
     * Download insta image.
     * 
     * @param fileName the file name
     */
    public void downloadInstaImage(final String fileName) {
        if (mCurrentFetcherData != null && mCurrentFetcherData.getImageUrl() != null) {
            final String absolutePath = InstaFileManager.INSTA_DOWNLOADER_FOLDER + fileName;
            final File file = new File(absolutePath);
            if (file.exists()) {
                String message = absolutePath + " exist ,are you sure continue download?";
                DialogUtil.showConfirmDialog(getActivity(), "Download Image", message,
                        new OnDialogListener() {

                            @Override
                            public void onPositive(String result) {
                                file.delete();
                                HistoryManager.getInstance().removeFromHistory(absolutePath);
                                if (!SdcardUtils.hasStorage()) {
                                    DialogUtility.alert(getInstaActivity(), "Canot start download.");
                                } else {
                                    getInstaActivity().getInstaDownloadManager().runDownload(
                                            mCurrentFetcherData.getImageUrl(),
                                            InstaFileManager.INSTA_DOWNLOADER_FOLDER, fileName,
                                            mDownloadListener);
                                }
                                getInstaActivity().setUrlImage(mCurrentFetcherData.getImageUrl());
                            }

                            @Override
                            public void onCancel() {}
                        });
            } else {
                String message = "do you want to download this image?";
                DialogUtil.showConfirmDialog(getActivity(), "Download Image", message,
                        new OnDialogListener() {

                            @Override
                            public void onPositive(String result) {
                                if (!SdcardUtils.hasStorage()) {
                                    DialogUtility.alert(getInstaActivity(), "Canot start download.");
                                } else {
                                    getInstaActivity().getInstaDownloadManager().runDownload(
                                            mCurrentFetcherData.getImageUrl(),
                                            InstaFileManager.INSTA_DOWNLOADER_FOLDER, fileName,
                                            mDownloadListener);
                                }
                            }

                            @Override
                            public void onCancel() {}
                        });
            }

        }
    }

    /**
     * Download insta video.
     * 
     * @param fileName the file name
     */
    public void downloadInstaVideo(final String fileName) {
        if (mCurrentFetcherData != null && mCurrentFetcherData.getVideoUrl() != null) {
            final String absolutePath = InstaFileManager.INSTA_DOWNLOADER_FOLDER + fileName;
            if (new File(absolutePath).exists()) {
                String message = absolutePath + " exist ,are you sure continue download?";
                DialogUtil.showConfirmDialog(getActivity(), "Download Video", message,
                        new OnDialogListener() {

                            @Override
                            public void onPositive(String result) {
                                new File(absolutePath).delete();
                                HistoryManager.getInstance().removeFromHistory(absolutePath);
                                if (!SdcardUtils.hasStorage()) {
                                    DialogUtility.alert(getInstaActivity(), "Canot start download.");
                                } else {
                                    getInstaActivity().getInstaDownloadManager().runDownload(
                                            mCurrentFetcherData.getVideoUrl(),
                                            InstaFileManager.INSTA_DOWNLOADER_FOLDER, fileName,
                                            mDownloadListener);
                                }
                            }

                            @Override
                            public void onCancel() {}
                        });
            } else {
                String message = "do you want to download this video?";
                DialogUtil.showConfirmDialog(getActivity(), "Download Video", message,
                        new OnDialogListener() {

                            @Override
                            public void onPositive(String result) {
                                if (!SdcardUtils.hasStorage()) {
                                    DialogUtility.alert(getInstaActivity(), "Canot start download.");
                                } else {
                                    getInstaActivity().getInstaDownloadManager().runDownload(
                                            mCurrentFetcherData.getVideoUrl(),
                                            InstaFileManager.INSTA_DOWNLOADER_FOLDER, fileName,
                                            mDownloadListener);
                                }
                            }

                            @Override
                            public void onCancel() {}
                        });
            }

        }
    }

    /**
     * Show input dialog image name.
     */
    public void showInputDialogImageName() {
        if (mCurrentFetcherData != null && mCurrentFetcherData.getImageUrl() != null
                && !mCurrentFetcherData.getImageUrl().trim().equals("")) {
            DialogUtil.showInputDialog(getActivity(), "Save Image", InstaFileManager.INSTA_DOWNLOADER_FOLDER,
                    new OnDialogListener() {

                        @Override
                        public void onPositive(String result) {
                            if (result != null && !result.trim().equals("")) {
                                result +=
                                        "."
                                                + FilenameUtils.getExtension(FilenameUtils
                                                        .getName(mCurrentFetcherData.getImageUrl()));
                                downloadInstaImage(result);
                            }
                        }

                        @Override
                        public void onCancel() {}
                    }, TextUtil.getFileName(mCurrentFetcherData.getImageUrl()));
        } else {
            DialogUtil.showConfirmDialog(getActivity(), "Warning", "Sorry, Image Not Found !");
        }

    }

    /**
     * Show input dialog video name.
     */
    public void showInputDialogVideoName() {
        if (mCurrentFetcherData != null && mCurrentFetcherData.getVideoUrl() != null
                && !mCurrentFetcherData.getVideoUrl().trim().equals("")) {
            DialogUtil.showInputDialog(getActivity(), "Save Video", InstaFileManager.INSTA_DOWNLOADER_FOLDER,
                    new OnDialogListener() {

                        @Override
                        public void onPositive(String result) {
                            if (result != null && !result.trim().equals("")) {
                                result +=
                                        "."
                                                + FilenameUtils.getExtension(FilenameUtils
                                                        .getName(mCurrentFetcherData.getVideoUrl()));
                                downloadInstaVideo(result);
                            }
                        }

                        @Override
                        public void onCancel() {}
                    }, TextUtil.getFileName(mCurrentFetcherData.getImageUrl()));
        } else {
            DialogUtil.showConfirmDialog(getActivity(), "Warning", "Sorry, Video Not Found !");
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.view.View.OnClickListener#onClick(android.view.View)
     */
    @Override
    public void onClick(View arg0) {
        switch (arg0.getId()) {
            case R.id.imageViewImagePost:
                showInputDialogImageName();
                break;
            case R.id.imageViewVideoPost:
                showInputDialogVideoName();
                break;
            case R.id.btnDownload:
                if (mEdtUrl.getText() != null) {
                    startFetchingUrl(mEdtUrl.getText().toString());
                }
                break;
            case R.id.btnPasteURL:
                getInstaActivity().sendLocalBroadcast(IDefines.AC_ADD_BOOKMARK);
                onPasteCopiedLink();
                break;
            case R.id.btnImage:
                if (!checkDownloading()) showInputDialogImageName();
                break;
            case R.id.btnVideo:
                if (!checkDownloading()) showInputDialogVideoName();
                break;
            case R.id.btnRepost:
                shareInstagramDirectly();
                break;
            case R.id.btnShare:
                AlertDialog.Builder b = new AlertDialog.Builder(getInstaActivity());
                b.setTitle("Options Share");
                String[] types = {"Share Instagram URK", "Share image and URL"};
                b.setSingleChoiceItems(types, 3, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        dialog.dismiss();
                        switch (which) {
                            case 0:
                                shareInstagramUrl();
                                break;
                            case 1:
                                shareInstagramImage();
                                break;
                        }
                    }

                });
                b.show();
                break;
            default:
                break;
        }

    }

    private void shareInstagramUrl() {
        Intent localIntent = new Intent("android.intent.action.SEND");
        localIntent.setType("text/plain");
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        localIntent.putExtra("android.intent.extra.SUBJECT", "instaDownloader");
        localIntent.putExtra("android.intent.extra.TEXT", this.currentUrl);
        getActivity().startActivity(Intent.createChooser(localIntent, "Choose Share"));
    }

    private void shareInstagramImage() {
        Intent localIntent = new Intent("android.intent.action.SEND");
        localIntent.setType("image/jpeg");
        localIntent.addFlags(524288);
        localIntent.putExtra("android.intent.extra.SUBJECT", "instaDownloader");
        localIntent.putExtra("android.intent.extra.TEXT", currentUrl);
        if (this.currentUrl != null && !currentUrl.isEmpty()) {
            localIntent.putExtra("android.intent.extra.STREAM",
                    Uri.fromFile(new File(getInstaActivity().getCurrentFileName())));
            getActivity().startActivity(Intent.createChooser(localIntent, "Options Share"));
        }
    }


    private void shareInstagramDirectly() {
        try {
            if (this.currentUrl != null && !this.currentUrl.isEmpty()) {
                Intent localIntent = new Intent("android.intent.action.SEND");
                localIntent.setType("image/*");
                localIntent.putExtra("android.intent.extra.STREAM",
                        Uri.fromFile(new File(getInstaActivity().getCurrentFileName())));
                localIntent.putExtra("android.intent.extra.TEXT", this.currentUrl);
                localIntent.setPackage("com.instagram.android");
                getActivity().startActivity(localIntent);
            }
            return;
        } catch (Exception localException) {
            Toast.makeText(getActivity(), "Unavailable official Instagram", 0).show();
        }
    }

    private void postInsta() {
        Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
        shareIntent.setType("image/*");

        final ContentResolver cr = getInstaActivity().getContentResolver();
        final String[] p1 =
                new String[] {MediaStore.Images.ImageColumns._ID, MediaStore.Images.ImageColumns.TITLE,
                        MediaStore.Images.ImageColumns.DATE_TAKEN};
        Cursor c1 = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, p1, null, null, p1[1] + " DESC");

        if (c1.moveToFirst()) {
            Log.i("Teste", "last picture (" + c1.getString(1) + ") taken on: " + new Date(c1.getLong(2)));
        }

        Log.i("Caminho download imagem", "file://" + Environment.getExternalStorageDirectory() + "/Tubagram/"
                + c1.getString(1) + ".png");

        shareIntent.putExtra(
                Intent.EXTRA_STREAM,
                Uri.parse("file://" + Environment.getExternalStorageDirectory() + "/Tubagram/"
                        + c1.getString(1) + ".png"));
        shareIntent.setPackage("com.instagram.android");

        c1.close();

        startActivity(shareIntent);
    }

    public void showDialogDownloadSucess(final String absolutePath) {
        DialogUtil.showOpenFileDialog(getActivity(), "Instagram Downloader", "Download File Success !", new OnDialogListener() {

            @Override
            public void onPositive(String result) {
                Launcher.openFile(getActivity(), absolutePath);
            }

            @Override
            public void onCancel() {

            }
        });
    }

    ProgressDialog barProgressDialog;
    HandlerDownload mHandlerDownload;

    @SuppressWarnings("deprecation")
    private ProgressDialog getProgressDialog() {
        if (barProgressDialog == null) {
            mHandlerDownload = new HandlerDownload();
            getInstaActivity().getInstaDownloadManager().setHandlerDownload(mHandlerDownload);
            barProgressDialog = new ProgressDialog(getInstaActivity());
            barProgressDialog.setTitle("Downloading Image ...");
            barProgressDialog.setMessage("Download in progress ...");
            barProgressDialog.setProgressStyle(barProgressDialog.STYLE_HORIZONTAL);
            barProgressDialog.setProgress(0);
            barProgressDialog.setMax(100);
            barProgressDialog.setButton("Move Background", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface arg0, int arg1) {
                    barProgressDialog.dismiss();
                }
            });
            barProgressDialog.setButton2("Cancel", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface arg0, int arg1) {
                    mHandlerDownload.setInteruptDownload(true);
                    barProgressDialog.dismiss();
                }
            });
        }
        return barProgressDialog;
    }

    // @Override
    public void onChanging(final double value) {
        if (barProgressDialog == null || !barProgressDialog.isShowing()) {
            getProgressDialog().show();
        }
        try {
            // barProgressDialog.incrementProgressBy((int) value);
            getProgressDialog().setProgress((int) value);
            if (barProgressDialog.getProgress() == barProgressDialog.getMax()) {
                getProgressDialog().dismiss();
            }
        } catch (Exception e) {}
    }

    public boolean isDownloading = false;

    public boolean checkDownloading() {
        if (isDownloading) {
            DialogUtil.showConfirmDialog(getActivity(), "Download File",
                    "Sorry, You're Downloading a file ,please wait... !");
            return true;
        } else {
            return false;
        }
    }

    public OnDownloadListener mDownloadListener = new OnDownloadListener() {

        @Override
        public void onProcessUpdate(int process) {
            if (mHandlerDownload != null && !mHandlerDownload.getDownloadAble()) return;
            if (barProgressDialog.isShowing()) onChanging(process);
        }

        @Override
        public void onDownloadSucess(String absolutePath) {
            isDownloading = false;
            ((MainActivity) getActivity()).onDownloadSucess(absolutePath);
            showDialogDownloadSucess(absolutePath);
        }

        @Override
        public void onDownloadPrepare() {
            isDownloading = true;
            if (mHandlerDownload != null) {
                mHandlerDownload.setInteruptDownload(false);
            }
            onChanging(0);
        }

        @Override
        public void onDownloadFail(String fail) {
            isDownloading = false;
            if (barProgressDialog.isShowing()) {
                barProgressDialog.dismiss();
            }
        }
    };

}
